<template>
  <div>
    <kv label="数据库连接">
      <db-conn :data="$props.data" ref="conn_com"></db-conn>

      <collection-ref :db-id="$props.data.id" v-model="info.table"
                      style="margin-left:60px;"
                      @change="collection_change"></collection-ref>

    </kv>


    <kv v-if="$props.type == 'esql'">
      <template #k>
        <div class="k">
          <div>ES|QL查询Json</div>

        </div>
      </template>
      <div style="display: flex;flex:1">
        <div style="display: flex;flex-direction: column;">
          <selector enum="EsqlPipelineCmdTypeEnum" v-model="$data.esqlKey"></selector>
          <el-button @click="key_click" style="font-size: 32px">✒</el-button>
        </div>
        <el-input type="textarea" v-model="info.esql" :autosize="{ minRows: 4, maxRows: 8 }"
                  style="flex:1;margin-left:8px;"></el-input>
      </div>
    </kv>
    <template v-else>
      <kv label="条件">
        <where ops="match" v-model="info.ui_wheres" :columns="getColumns($data.previewData)"></where>
      </kv>
      <kv label="排序">
        <el-autocomplete
            v-model="info.sort"
            :fetch-suggestions="querySearch"
            clearable
            style="width:180px;"
        />

        <selector :data="{true: '升序', false:'降序'}" v-model="info.sortAsc"></selector>
      </kv>
    </template>
    <div style="display: flex">
      <kv>
        <el-button @click="view_click" style="margin-left: 200px">预览</el-button>

        <el-button type="primary" @click="ok_click()" style="margin-left: 200px">导出</el-button>

        <div style="display: flex;flex-wrap:nowrap; margin-left: 10px;">
          <el-input v-model="info.skip" style="width:160px;">
            <template slot="prepend">skip</template>
          </el-input>
          <el-input v-model="info.take" style="width:160px;margin-left: 20px;">
            <template slot="prepend">take</template>
          </el-input>
        </div>
      </kv>
    </div>
    <preview-json-table ref="table" :model-value="$data.previewData" v-loading="$data.loading"
                        :currentPage.sync="$data.pageNumber"
                        @pager-change="pager_change" @delete="table_delete"></preview-json-table>
  </div>
</template>

<style lang="scss" scoped>

::v-deep(.kv) {
  .k {
    max-width: 180px;
  }

  .v {

    > :first-child {
      max-width: unset;
    }
  }
}

</style>
<script setup>
/**
 * Created by CodeGenerator  at 2021-03-15 10:31:23
 */
import dbConn from "../../../component/db-conn.vue"
import collectionRef from "./collection-ref.vue"
import previewJsonTable from "../../../component/preview-json-table.vue";
import where from "../../../component/where.vue"


defineOptions({
  name: "export",
  inheritAttrs: true,
});

//定义 vue2的this,当前组件
const $self = getCurrentInstance();

//定义 $attrs
const $attrs = useAttrs();

const querySearch = (queryString, cb) => {
  var list = getColumns($data.previewData).filter(it => it.includes(queryString));
  cb(list.map(it => {
    return {value: it}
  }));
}


//定义data
const $data = reactive({
  loading:false,
  previewData: {},
  pageNumber: 1,
  esqlKey: "",
  info: {
    connectionUri: "http://es:9200",
    table: "",
    ui_wheres: [],
    wheres: [],
    excludes: "",
    skip: 0,
    take: 1000
  }, //子对象需要声明。
});

const info = $computed(() => $data.info);

const $props = defineProps({
  data: {type: Object},
  type: {type: String, default: "esql"},
});

const conn_com = ref();

const list = ref();

//定义事件
const $emit = defineEmits(["update:modelValue", "loaded"]);

const getColumns = v => {
  if (!v.data || !v.data.length) {
    return [];
  }

  return Object.keys(v.data[0])
}

const key_click = () => {
  if (info.esql) {
    info.esql = info.esql + ('\n| ' + $data.esqlKey)
  } else {
    info.esql = ('| ' + $data.esqlKey)
  }
}
const action_name = $computed(function () {
  return {add: "添加", edit: "修改"}[$props.action]
});

const collection_change = function (v) {
  jv.$saveData("es-exp-table", info.table);
  $data.info.wheres = [];

  $data.pageNumber = 1;

  info.esql = "";
  info.ui_wheres = [];
};
// const collection_click = function (p) {
// //校验
//   if (conn_com.value.$el.chk($data.info) == false) {
//     p.returnValue = false;
//     return;
//   }
//   pager_change()
// };
const view_click = function () {
//校验
  if (conn_com.value.$el.chk($data.info) == false) {
    return;
  }

  $data.pageNumber = 1;
  pager_change();
};
const pager_change = function (p) {
  if (!$props.data.connectionUri) {
    return;
  }
  var info = Object.assign({}, $data.info, {type: $props.type});
  if (p) {
    info.skip = (p.pageNumber - 1) * p.pageSize;
    info.take = p.pageSize;
  } else {
    info.skip = 0;
    info.take = 15;
  }
  info.wheres = info.ui_wheres.filter(it => it.column && it.op);
  if (!info.table) {
    return;
  }
  delete info.ui_wheres;

  info.connectionUri = $props.data.connectionUri;

  $data.loading = true;
  jv.$http.post("/dev/es/get-data/" + $props.data.id, info).then(res => {
    $data.previewData = res.data;
    $data.loading = false;
  }).catch(err => {
    $data.loading = false;
  })
};
const ok_click = function () {
//校验
  if (conn_com.value.$el.chk() == false) {
    return;
  }
  jv.$saveData("info", $data.info)
  var info = Object.assign({}, $data.info, {type: $props.type});
  info.wheres = info.ui_wheres.filter(it => it.column && it.op);
  delete info.ui_wheres;
  jv.$http.downloadWithPost("/dev/es/export/" + $props.data.id, Object.assign({}, info, {connectionUri: $props.data.connectionUri}))
};
const table_delete = function (row) {
  var rowId = row._id || row.id;
  var json = {};
  json.table = $data.info.table;
  json.rowId = rowId;
  json.connectionUri = $props.data.connectionUri;

  jv.$http.post("/dev/es/delete-id/" + $props.data.id, json).then(res => {
    pager_change();
  })
};

onMounted(function () {
  jv.$loadData("es-exp-table", v => $data.info.table = v)

  if (!$data.info.ui_wheres) {
    $data.info.ui_wheres = [];
  }

  if ($data.info.table) {
    pager_change();
  }
})


</script>
